package type.pets;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Date 2021/4/29 6:56 下午
 * @Author dengxin
 */
public class PetCounter extends HashMap<Class<?>, Integer> {

    private Class<?> baseType;

    public PetCounter(Class<Pet> baseType) {
        this.baseType = baseType;
    }

    public void count(Object obj) throws Exception {
        if (!baseType.isAssignableFrom(obj.getClass())) {
            throw new Exception("Input Type Error!");
        }
        countClass(obj);
    }

    private void countClass(Object obj) throws Exception {
        Class<?> clazz = obj.getClass();
        put(clazz, null == get(clazz) ? 0 : get(clazz) + 1);
        Class<?> superClazz = clazz.getSuperclass();
        if (superClazz != null && baseType.isAssignableFrom(superClazz)) {
            try {
                count(superClazz.newInstance());
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<Class<?>, Integer> entry : entrySet()) {
            sb.append("type ").append(entry.getKey().getSimpleName()).append(", count ").append(entry.getValue()).append(".  ");
        }
        return sb.toString();
    }
}
